/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.hycreate.platform.modules.crm.workbench;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hycreate.platform.common.config.Global;
import com.hycreate.platform.common.utils.StringUtils;
import com.hycreate.platform.common.web.BaseController;
import com.hycreate.platform.modules.crm.business.HycrmContact;
import com.hycreate.platform.modules.crm.business.SysDictService;
import com.hycreate.platform.modules.crm.findcustomer.FindCustomerContact;
import com.hycreate.platform.modules.crm.findcustomer.FindCustomerRecord;
import com.hycreate.platform.modules.crm.findcustomer.FindCustomerService;
import com.hycreate.platform.modules.sys.entity.Area;
import com.hycreate.platform.modules.sys.service.AreaService;
import com.hycreate.platform.modules.sys.utils.UserUtils;


/**
 * 工作态的主体功能Controller
 * @author zzf
 * @version 2016-12-03
 */
@Controller
@RequestMapping(value = "${adminPath}/crm/workbench/workbench")
public class WorkbenchController extends BaseController {

	@Autowired
	private WorkbenchService workbenchService;

	@Autowired
	private SysDictService dictService;

	@Autowired
	private FindCustomerService findCustomerService;
	@Autowired
	private AreaService areaService;

	@ModelAttribute
	public Workbench get(@RequestParam(required=false) String id) {
		Workbench entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workbenchService.get(id);
		}
		if (entity == null){
			entity = new Workbench();
		}
		return entity;
	}

	/**
	 * 
	 * 工作空间的主显示数据信息
	 * @author zzf 
	 * @return
	 */
	@RequiresPermissions("workbench:workbench:view")
	@RequestMapping(value = {"list", ""})
	public String list( Model model) {
		String  userid=UserUtils.getUser().getId();  //获得当前用户的ID

		List<Workbench> list1=new ArrayList<Workbench>(); //被选择的客户的集合
		List<FindCustomerContact> list2=new ArrayList<FindCustomerContact>(); //被选择客户的联系方式
		List<Workbench> list3=new ArrayList<Workbench>();  //被选择客户的行业集合，
		List<String> industryNames=new ArrayList<String>();  //给前台下拉列表里的行业准备的集合
		List<Area> area=areaService.findAllProvince();
		StringBuffer industryBuffer=new StringBuffer("");//用StringBuffer拼接行业字段
		int  count=0; //被选择的客户的数量，初始为零


		industryNames=	dictService.findAllIndustryNames();//前台下拉列表里的行业

		int isnull=	workbenchService.selectnull(userid);  //判断是否有被选中的客户


		if(isnull>0){
			count=workbenchService.SelectCount(userid);  //得到被选择的客户的数量

			if(count>0){
				list1=workbenchService.getWorkbenchs(userid); //获得被选择的客户
				if(list1.size()>0){
					String Customerid=list1.get(0).getId(); //从中抽取一个对象
					list2= workbenchService.getWorkbenchContact(Customerid); //根据这个对象的，查找他的关键人
					list3=workbenchService.getIndustry(Customerid);  //根据这个对象的，获得它的行业
					for (Workbench workbenchindutry : list3) {
						industryBuffer.append(workbenchindutry.getIndustry()+","); //用StringBuffer拼接行业字段
					}
					if(industryBuffer.toString().equals("")){
						industryBuffer.append("暂无,");
					}
					model.addAttribute("customer", list1.get(0));
				}

			}

		}else{
			workbenchService.deleteQuantity(userid);
		}




		model.addAttribute("industryNames", industryNames);
		model.addAttribute("contact", list2);
		model.addAttribute("industry", industryBuffer);
		model.addAttribute("count", count);
		model.addAttribute("area",area);

		return "modules/crm/workbench/workbenchList";
	}

	@RequiresPermissions("workbench:workbench:view")
	@RequestMapping(value = "form")
	public String form(Workbench workbench, Model model) {
		model.addAttribute("workbench", workbench);
		return "modules/crm/workbench/workbenchForm";
	}

	@RequiresPermissions("workbench:workbench:workstart")
	@RequestMapping(value = "CustomerSelect")
	public String  Customer(String industryNames ,String selectstatus,String province,String city,RedirectAttributes redirectAttributes,Model model ){
		String userid=UserUtils.getUser().getId();
		WorkBenchUseridupdate wbuu=null;
		CustomerCount count=null;

		List<String> industry=new ArrayList<String>();
		industry=	dictService.findAllIndustryNames();

		WorkbenchCustomerSelect workselct=new WorkbenchCustomerSelect(industryNames, selectstatus, province,city);

		workbenchService.deleteQuantity(userid);//删除数据重复数据
		List<Workbench> list= workbenchService.SelectCustomer(workselct); //查询客户


		int countnumb=list.size();

		if(countnumb>0){
			count=new CustomerCount(userid, countnumb);   

			workbenchService.addUserCustomerCount(count);

			for (Workbench workbench : list) {
				wbuu=new WorkBenchUseridupdate(workbench.getId(), userid);
				workbenchService.updateuserId(wbuu);
			}
			List<Area> area=areaService.findAllProvince();
			model.addAttribute("area", area);
			return 	"redirect:"+Global.getAdminPath()+"/crm/workbench/workbench/list";

		}else{

			List<Area> area=areaService.findAllProvince();
			model.addAttribute("area", area);
			String 	message="该条件暂无可用客户";

			model.addAttribute("message", message);

			model.addAttribute("industryNames", industry);
			return "modules/crm/workbench/workbenchList"; 
		}




	}

	/**
	 * 
	 * @param model
	 * @return
	 */
	//新增的列表（--！）
	@RequestMapping(value = "workbenchselect")
	public String  workbenchSelect(Model model) {

		String userid=UserUtils.getUser().getId();
		List<Workbench> list =	workbenchService.getWorkbenchs(userid);

		model.addAttribute("findCustomerList", list);

		return "modules/crm/workbench/WorkbenchSelect";
	}

	//列表的数据释放
	@RequestMapping(value = "release")
	public String  listRelease(String customerId ,Model model) {

		workbenchService.workbenchskip(customerId);
		String  userid=UserUtils.getUser().getId();
		workbenchService.updateQuantity(userid);//给当前用户的客户数量减一
		return "redirect:"+Global.getAdminPath()+"/crm/workbench/workbench/workbenchselect";
	}

	//列表的选择操作
	@RequestMapping(value = "pitchOn")
	public String listSelect(String customerId ,Model model) {
		String  userid=UserUtils.getUser().getId();  //获得当前用户的ID

		Workbench wb=new Workbench(); //被选择的客户的集合
		List<FindCustomerContact> listContact=new ArrayList<FindCustomerContact>(); //被选择客户的联系方式
		List<Workbench> list3=new ArrayList<Workbench>();  //被选择客户的行业集合，
		List<String> industryNames=new ArrayList<String>();  //给前台下拉列表里的行业准备的集合
		StringBuffer industryBuffer=new StringBuffer("");//用StringBuffer拼接行业字段
		int  count=0; //被选择的客户的数量，初始为零


		industryNames=	dictService.findAllIndustryNames();//前台下拉列表里的行业

		int isnull=	workbenchService.selectnull(userid);  //判断是否有被选中的客户


		if(isnull>0){
			count=workbenchService.SelectCount(userid);  //得到被选择的客户的数量

			if(count>0){
				wb=workbenchService.get(customerId); //获得被选择的客户
				if(wb !=null){

					workbenchService.updateCurrentCustomerIsNull(userid);
					workbenchService.updateCurrntCustomer(customerId, userid);

					listContact= workbenchService.getWorkbenchContact(customerId); //根据这个对象的，查找他的关键人
					list3=workbenchService.getIndustry(customerId);  //根据这个对象的，获得它的行业
					for (Workbench workbenchindutry : list3) {
						industryBuffer.append(workbenchindutry.getIndustry()+","); //用StringBuffer拼接行业字段
					}
					if(industryBuffer.toString().equals("")){
						industryBuffer.append("暂无,");
					}
					model.addAttribute("customer", wb);



				}
			}

		}else{
			workbenchService.deleteQuantity(userid);
		}
		model.addAttribute("industryNames", industryNames);
		model.addAttribute("contact", listContact);
		model.addAttribute("industry", industryBuffer);
		model.addAttribute("count", count);

		return "modules/crm/workbench/workbenchList";
	}

	/**
	 * 
	 * 一开始next就是下一个，后来改了名叫保存，省事不该了
	 */
	@RequiresPermissions("workbench:workbench:next")
	@RequestMapping(value = "next")
	public String  next(String statusId,String content,String customerid,Model model) {
		String  userid=UserUtils.getUser().getId();
		FindCustomerRecord record=new FindCustomerRecord();
		record.setAddress("电话联系");
		record.setCustomerId(customerid);
		record.setCreateUserId(userid);
		record.setContent(content);
		WorkbenchFiledTemp filed =new WorkbenchFiledTemp(statusId, null, customerid, userid);

		String isnull= workbenchService.usridIsNull(customerid);
		if(isnull !=null){


			Integer isZero=	workbenchService.selectquantityIszero(userid);
			workbenchService.addCustomerContactRecord(record);  //添加公司的联系记录
			workbenchService.workbenchnext(filed);  //下一个的方法，改变公司状态、公司的最近联系时间、还有把公司的userid属性改为null


			workbenchService.updateQuantity(userid);//给当前用户的客户数量减一

			workbenchService.updateAccomplish(userid); //改变当月用户的工作量

			return "redirect:"+Global.getAdminPath()+"/crm/workbench/workbench/list";
		}else{

			String 	message="该信息错误，有可能已被修改，请检查账户！";   //同一账户数据冲突处理

			model.addAttribute("message", message);

			return "modules/crm/workbench/workbenchList"; 
		}


	}


	@RequiresPermissions("workbench:workbench:skip")
	@RequestMapping(value = "skip")
	public String  skip(String customerid ,Model model) {
		String  userid=UserUtils.getUser().getId();
		String isnull= workbenchService.usridIsNull(customerid);
		if(isnull !=null){

			Integer isZero=	workbenchService.selectquantityIszero(userid);
			workbenchService.workbenchskip(customerid);  //跳过的方法，不改变任何属性，但是释放userid，让它为null

			workbenchService.updateQuantity(userid);//给当前用户的客户数量减一

			return "redirect:"+Global.getAdminPath()+"/crm/workbench/workbench/list";
		}else{

			String 	message="该信息错误，有可能已被修改，请检查账户！";  //同一账户数据冲突处理

			model.addAttribute("message", message);

			return "modules/crm/workbench/workbenchList"; 
		}





	}

	@RequiresPermissions("workbench:workbench:view")
	@RequestMapping(value = "contact")  //关键人的联系方式，二级联动
	public  void getDepartment(String contactId,HttpServletRequest req, HttpServletResponse resp ) throws JsonGenerationException, JsonMappingException, IOException {
		HycrmContact ContactWays= workbenchService.getContactWays(contactId);
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(ContactWays);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().print(json);
	}

	@RequiresPermissions("workbench:workbench:collection")
	@RequestMapping(value = "collection")  //用户的客户收藏
	public  void addcollection(String customerid,RedirectAttributes redirectAttributes,HttpServletResponse resp) throws IOException {
		String  userid=UserUtils.getUser().getId();
		WorkbenchNextFiled filed=new WorkbenchNextFiled(null, null, customerid, userid);
		String findCustomer = findCustomerService.alreadyCollect(customerid);
		if(findCustomer == null){


			workbenchService.addcollect(filed);
			resp.setContentType("application/text;charset=utf-8");
			resp.getWriter().print("1");



		}else{

			int isExist=workbenchService.CollectExist(filed);  //判断这个客户是否已被收藏

			if(isExist==0){
				resp.setContentType("application/text;charset=utf-8");
				resp.getWriter().print("-1");
			}else{
				resp.setContentType("application/text;charset=utf-8");
				resp.getWriter().print("2");
			}



		}




	}

	@RequiresPermissions("workbench:workbench:edit")
	@RequestMapping(value = "delete")
	public String delete(Workbench workbench, RedirectAttributes redirectAttributes) {
		workbenchService.delete(workbench);
		addMessage(redirectAttributes, "删除联系成功");
		return "redirect:"+Global.getAdminPath()+"/crm/workbench/workbench/?repage";
	}

}